<template>
  <el-row type="flex" justify="center" align="middle" class="container">
    <el-col class="custom-box">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        status-icon
      >
        <el-form-item label="账号" prop="account" :rules="rules.account">
          <el-input
            v-model="ruleForm.account"
            v-debounce:500="onSearchUsername"
            :placeholder="placeInfo"
            clearable
            @input="onInput"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
            v-model="ruleForm.pass"
            show-password
            :placeholder="passwordInfo"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            v-model="ruleForm.checkPass"
            show-password
            :placeholder="passwordInfo"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-col :span="12" class="custom-btn">
            <el-button type="primary" @click="onSubmit('ruleForm')"
              >提交</el-button
            >
          </el-col>
          <el-col :span="12" class="custom-btn">
            <el-button @click="onBack">返回</el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { checkAccount } from "@/apis/Account";
import { regist } from "@/utils/account";
import { getReqDataNew } from "@/utils/http";
import { successResponseType, failRejectType } from "CustomTypes";
import { isUndefined } from "lodash";

@Component({
  name: "Regist"
})
export default class Regist extends Vue {
  private min = 5;
  private max = 10;
  inputContent = "";
  placeInfo = `请输入${this.min} 到 ${this.max}位数的账号`;
  passwordInfo = `请输入${this.min}-${this.max}位密码`;
  formData: any;
  accountUseful = false;

  ruleForm = {
    account: "",
    pass: "",
    checkPass: ""
  };

  rules = {
    account: [
      { required: true, message: "请输入账号", trigger: "blur" },
      {
        min: this.min,
        max: this.max,
        message: `长度在 ${this.min} 到 ${this.max} 个字符`,
        trigger: "blur"
      }
    ],
    pass: [
      {
        min: this.min,
        max: this.max,
        message: `密码的长度需要在 ${this.min} 到 ${this.max} 个字符之间`,
        trigger: "blur"
      },
      { required: true, validator: this.validatePass, trigger: "blur" }
    ],
    checkPass: [
      {
        min: this.min,
        max: this.max,
        message: `密码的长度需要在 ${this.min} 到 ${this.max} 个字符之间`,
        trigger: "blur"
      },
      { required: true, validator: this.validatePass2, trigger: "blur" }
    ]
  };

  validatePass(rule: any, value: any, callback: any) {
    if (value === "") {
      callback(new Error("请输入密码"));
    } else {
      if (this.ruleForm.checkPass !== "") {
        const temp: any = this.$refs.ruleForm;
        temp.validateField("checkPass");
      }
      callback();
    }
  }

  validatePass2(rule: any, value: any, callback: any) {
    if (value === "") {
      callback(new Error("请再次输入密码"));
    } else if (value !== this.ruleForm.pass) {
      callback(new Error("两次输入密码不一致!"));
    } else {
      callback();
    }
  }

  /**
   * 使用 vue-debounce 之后，可以运行这个。
   */
  onSearchUsername() {
    checkAccount(this.inputContent)
      .then((res: successResponseType) => {
        const { flag } = getReqDataNew(res);
        if (!flag) {
          this.accountUseful = true;
          return null;
        }
        this.accountUseful = false;
        this.$notify.error({
          title: "错误",
          message: "用户名已被占用"
        });
      })
      .catch((error: failRejectType) => {
        console.log("error", error);
      });
  }

  onInput(e: string) {
    this.inputContent = e;
  }

  onSubmit(formName: string) {
    if (!this.accountUseful) {
      this.$notify.error({
        title: "错误",
        message: "用户名已被占用"
      });
      return null;
    }
    this.formData = this.$refs[formName];
    this.formData.validate(async (valid: any) => {
      if (valid) {
        const flag = await regist(this.ruleForm.account, this.ruleForm.pass);
        if (!isUndefined(flag)) {
          this.onBack();
        }
      } else {
        this.$notify.error({
          title: "错误",
          message: "注册失败"
        });
        return false;
      }
    });
  }

  onBack() {
    this.$router.back();
  }
}
</script>

<style>
.container {
  height: 100% !important;
}
.custom-box {
  width: fit-content;
  margin-left: -80px;
}
.custom-btn {
  display: flex;
  align-content: center;
  justify-content: center;
}
</style>
